<template>
  <div class="learning-tasks">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">{{ $t('assets.learningTasks.title') }}</h1>
    </div>

    <!-- 分类标签栏 + 创建按钮 -->
    <div class="status-tabs">
      <div class="tabs-left">
        <el-tabs v-model="activeCategory" @tab-change="handleCategoryChange">
          <el-tab-pane :label="$t('assets.learningTasks.all')" name="all" />
          <el-tab-pane :label="$t('assets.learningTasks.pending')" name="pending" />
          <el-tab-pane :label="$t('assets.learningTasks.correction')" name="correction" />
          <el-tab-pane :label="$t('assets.learningTasks.completed')" name="completed" />
        </el-tabs>
      </div>
      <div class="tabs-right">
        <el-button type="primary" @click="createTask">
          {{ $t('assets.learningTasks.createTask') }}
        </el-button>
      </div>
    </div>

    <!-- 筛选功能栏 -->
    <div class="filter-section">
      <el-form :inline="true" :model="filterForm" class="search-form">
        <el-form-item :label="$t('assets.learningTasks.taskName') + ':'">
          <el-input v-model="filterForm.taskName" :placeholder="$t('assets.learningTasks.pleaseEnterTaskName')" clearable @input="handleSearch"
            style="width: 200px;" />
        </el-form-item>
        <el-form-item :label="$t('assets.learningTasks.subjectType') + ':'">
          <el-select v-model="filterForm.subjects" :placeholder="$t('assets.learningTasks.pleaseSelectSubject')" multiple clearable @change="handleSearch"
            style="width: 200px;">
            <el-option :label="$t('assets.subjects.math')" value="math" />
            <el-option :label="$t('assets.subjects.chinese')" value="chinese" />
            <el-option :label="$t('assets.subjects.english')" value="english" />
            <el-option :label="$t('assets.subjects.other')" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('assets.learningTasks.taskTime') + ':'">
          <el-date-picker
            v-model="filterForm.selectedDate"
            type="date"
            :placeholder="$t('assets.learningTasks.selectDate')"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            @change="handleSearch"
            style="width: 180px;"
            :teleported="false"
          />
        </el-form-item>
        <el-form-item>
          <el-button @click="resetFilter">{{ $t('common.reset') }}</el-button>
          <el-button type="primary" @click="searchTasks">{{ $t('common.search') }}</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 学习任务列表 -->
    <div class="tasks-table-section">
      <el-table :data="filteredTasks" style="width: 100%" class="tasks-table">
        <el-table-column :label="$t('assets.learningTasks.dataName')" min-width="300">
          <template #default="scope">
            <div class="task-name-cell">
              <div class="task-icon">
                <img :src="getSubjectIcon(scope.row.subject)" :alt="scope.row.subject" />
              </div>
              <div class="task-info">
                <div class="task-title">{{ scope.row.title }}</div>
                <div class="task-description">{{ scope.row.description }}</div>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column :label="$t('assets.learningTasks.taskTimeColumn')" min-width="200">
          <template #default="scope">
            <div class="task-time">
              {{ formatTaskTime(scope.row.startTime, scope.row.endTime) }}
            </div>
          </template>
        </el-table-column>

        <el-table-column :label="$t('assets.learningTasks.statusColumn')" min-width="150">
          <template #default="scope">
            <div class="task-status">
              <div v-for="status in scope.row.statusList" :key="status.type" class="status-item"
                :class="{ completed: status.completed }">
                <img :src="status.completed ? completeIcon : pendingIcon" :alt="status.label" class="status-icon" />
                <span class="status-label">{{ status.label }}</span>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column :label="$t('assets.learningTasks.operation')" min-width="300">
          <template #default="scope">
            <div class="task-actions">
              <el-button v-for="action in getTaskActions(scope.row)" :key="action.key" type="primary" link
                @click="handleAction(action.key, scope.row)">
                {{ action.label }}
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-section">
        <el-config-provider :locale="zhCn">
          <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 50, 100]"
            :total="totalTasks" layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </el-config-provider>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { t as $t } from '@/plugins/simpleI18n'
import { photosStorage, type PhotoData } from '@/utils/photosDB'
import zhCn from 'element-plus/es/locale/lang/zh-cn'

const router = useRouter()

// 类型定义
interface TaskStatus {
  type: string
  label: string
  completed: boolean
}

interface LearningTask {
  id: number
  title: string
  description: string
  subject: string
  startTime: string
  endTime: string
  statusList: TaskStatus[]
}

interface FilterForm {
  taskName: string
  subjects: string[]
  selectedDate: string
}

interface Category {
  key: string
  label: string
}

interface TaskAction {
  key: string
  label: string
}

type CategoryKey = 'all' | 'pending' | 'correction' | 'completed'
type SubjectKey = 'math' | 'chinese' | 'english' | 'other'

// 响应式数据
const activeCategory = ref<CategoryKey>('all')
const currentPage = ref(1)
const pageSize = ref(10)

// 筛选表单
const filterForm = ref<FilterForm>({
  taskName: '',
  subjects: [],
  selectedDate: ''
})

// 分类数据
const categories = ref<Category[]>([
  { key: 'all', label: $t('assets.learningTasks.all') },
  { key: 'pending', label: $t('assets.learningTasks.pendingGrading') },
  { key: 'correction', label: $t('assets.learningTasks.needCorrection') },
  { key: 'completed', label: $t('assets.learningTasks.completedStatus') }
])

// 图标资源
const completeIcon = new URL('@/assets/complete.png', import.meta.url).href
const pendingIcon = new URL('@/assets/pending.png', import.meta.url).href

// 学习任务数据
const learningTasks = ref<LearningTask[]>([
  {
    id: 1,
    title: '这里是数学任务',
    description: '这里是一段数学任务描述',
    subject: 'math',
    startTime: '2025-04-23',
    endTime: '2025-05-23',
    statusList: [
      { type: 'created', label: $t('assets.learningTasks.created'), completed: true },
      { type: 'grading', label: $t('assets.learningTasks.grading'), completed: false },
      { type: 'correction', label: $t('assets.learningTasks.correction'), completed: false }
    ]
  },
  {
    id: 2,
    title: '这里是数学任务',
    description: '这里是一段数学任务描述',
    subject: 'math',
    startTime: '2025-04-23',
    endTime: '2025-05-23',
    statusList: [
      { type: 'created', label: $t('assets.learningTasks.created'), completed: true },
      { type: 'grading', label: $t('assets.learningTasks.grading'), completed: true },
      { type: 'correction', label: $t('assets.learningTasks.correction'), completed: false }
    ]
  },
  {
    id: 3,
    title: '这里是数学任务',
    description: '这里是一段数学任务描述',
    subject: 'chinese',
    startTime: '2025-04-23',
    endTime: '2025-05-23',
    statusList: [
      { type: 'created', label: $t('assets.learningTasks.created'), completed: true },
      { type: 'grading', label: $t('assets.learningTasks.grading'), completed: true },
      { type: 'correction', label: $t('assets.learningTasks.correctionSuccess'), completed: true }
    ]
  },
  {
    id: 4,
    title: '这里是数学任务',
    description: '这里是一段数学任务描述',
    subject: 'english',
    startTime: '2025-04-23',
    endTime: '2025-05-23',
    statusList: [
      { type: 'created', label: $t('assets.learningTasks.created'), completed: true },
      { type: 'grading', label: $t('assets.learningTasks.grading'), completed: true },
      { type: 'correction', label: $t('assets.learningTasks.correctionSuccess'), completed: true }
    ]
  },
  {
    id: 5,
    title: '这里是数学任务',
    description: '这里是一段数学任务描述',
    subject: 'math',
    startTime: '2025-04-23',
    endTime: '2025-05-23',
    statusList: [
      { type: 'created', label: $t('assets.learningTasks.created'), completed: true },
      { type: 'grading', label: $t('assets.learningTasks.grading'), completed: false },
      { type: 'correction', label: $t('assets.learningTasks.correction'), completed: false }
    ]
  }
])

// 计算属性
const filteredTasks = computed(() => {
  let filtered = learningTasks.value

  // 按分类筛选
  if (activeCategory.value !== 'all') {
    filtered = filtered.filter((task: LearningTask) => {
      const statusMap: Record<CategoryKey, (task: LearningTask) => boolean> = {
        'all': () => true,
        'pending': (task: LearningTask) => task.statusList.some((s: TaskStatus) => s.type === 'grading' && !s.completed),
        'correction': (task: LearningTask) => task.statusList.some((s: TaskStatus) => s.type === 'correction' && !s.completed),
        'completed': (task: LearningTask) => task.statusList.every((s: TaskStatus) => s.completed)
      }
      return statusMap[activeCategory.value]?.(task) || false
    })
  }

  // 按筛选条件过滤
  if (filterForm.value.taskName) {
    filtered = filtered.filter((task: LearningTask) =>
      task.title.includes(filterForm.value.taskName)
    )
  }

  if (filterForm.value.subjects.length > 0) {
    filtered = filtered.filter((task: LearningTask) =>
      filterForm.value.subjects.includes(task.subject)
    )
  }

  if (filterForm.value.selectedDate) {
    filtered = filtered.filter((task: LearningTask) =>
      task.startTime.includes(filterForm.value.selectedDate)
    )
  }

  return filtered
})

const totalTasks = computed(() => filteredTasks.value.length)

// 方法
const getSubjectIcon = (subject: string) => {
  const iconMap: Record<string, string> = {
    math: new URL('@/assets/task.png', import.meta.url).href,
    chinese: new URL('@/assets/TeachingTasks.png', import.meta.url).href,
    english: new URL('@/assets/home01.png', import.meta.url).href,
    other: new URL('@/assets/home02.png', import.meta.url).href
  }
  return iconMap[subject] || iconMap.other
}

const formatTaskTime = (startTime: string, endTime: string) => {
  return `${startTime} 至 ${endTime}`
}

const getTaskActions = (task: LearningTask): TaskAction[] => {
  const allCompleted = task.statusList.every((s: TaskStatus) => s.completed)
  const hasGrading = task.statusList.some((s: TaskStatus) => s.type === 'grading' && s.completed)
  const hasCreated = task.statusList.some((s: TaskStatus) => s.type === 'created' && s.completed)
  const needsCorrection = task.statusList.some((s: TaskStatus) => s.type === 'correction' && !s.completed)

  if (allCompleted) {
    // 三个状态全部成功：详情、作业详情、错题集
    return [
      { key: 'detail', label: $t('assets.learningTasks.detail') },
      { key: 'homework-detail', label: $t('assets.learningTasks.homeworkDetail') },
      { key: 'error-collection', label: $t('assets.learningTasks.errorCollection') }
    ]
  } else if (hasCreated && hasGrading && needsCorrection) {
    // 创建、批改完成状态：详情、错题集、去订正、作业详情
    return [
      { key: 'detail', label: $t('assets.learningTasks.detail') },
      { key: 'error-collection', label: $t('assets.learningTasks.errorCollection') },
      { key: 'correction', label: $t('assets.learningTasks.goCorrection') },
      { key: 'homework-detail', label: $t('assets.learningTasks.homeworkDetail') }
    ]
  } else if (hasCreated && !hasGrading) {
    // 仅创建状态：详情、上传作业
    return [
      { key: 'detail', label: $t('assets.learningTasks.detail') },
      { key: 'upload', label: $t('assets.learningTasks.uploadHomework') }
    ]
  }

  return [{ key: 'detail', label: $t('assets.learningTasks.detail') }]
}

const handleAction = (actionKey: string, task: LearningTask) => {
  switch (actionKey) {
    case 'detail':
      // 跳转到任务详情页
      router.push({
        name: 'homework-submission-detail',
        params: { taskId: task.id }
      })
      break
    case 'upload':
      // 跳转到拍摄页面
      router.push({
        name: 'camera-capture',
        params: { taskId: task.id },
        query: {
          fromRoute: 'learning-tasks',
          context: 'homework-upload'
        }
      })
      break
    case 'correction':
      // 跳转到拍摄页面（订正作业）
      router.push({
        name: 'camera-capture',
        params: { taskId: task.id, mode: 'correction' },
        query: {
          fromRoute: 'learning-tasks',
          context: 'homework-correction'
        }
      })
      break
    case 'homework-detail':
      // 跳转到作业详情页
      router.push({
        name: 'homework-detail-view',
        params: { taskId: task.id }
      })
      break
    case 'error-collection':
      // 跳转到错题集页面
      router.push({
        name: 'error-collection',
        params: { taskId: task.id }
      })
      break
    default:
      ElMessage.info(`执行操作: ${actionKey}`)
  }
}

const createTask = () => {
  router.push('/student/learning-tasks/create')
}

const resetFilter = () => {
  filterForm.value = {
    taskName: '',
    subjects: [],
    selectedDate: ''
  }
}

const searchTasks = () => {
  ElMessage.success('查询完成')
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
}

const handleCategoryChange = (categoryKey: string) => {
  activeCategory.value = categoryKey as CategoryKey
}

const handleSearch = () => {
  // 搜索逻辑已在 computed 中实现
  console.log('执行搜索', filterForm.value)
}

// 图片处理相关方法
const handleTaskImageUpload = async (taskId: number, photoData: PhotoData) => {
  try {
    // 为任务图片添加特殊标记
    const taskPhoto = {
      ...photoData,
      category: 'learning-task',
      taskId: taskId,
      uploadTime: new Date().toISOString()
    }

    await photosStorage.savePhoto(taskPhoto)
    ElMessage.success($t('common.photoSavedSuccess'))

    console.log('任务图片已保存:', taskPhoto)
  } catch (error) {
    console.error('保存任务图片失败:', error)
    ElMessage.error($t('common.photoSaveError'))
  }
}

// 从本地存储加载任务相关图片
const loadTaskPhotos = async (taskId?: number) => {
  try {
    const photos = await photosStorage.getAllPhotos()
    const taskPhotos = photos.filter(photo =>
      photo.category === 'learning-task' &&
      (!taskId || photo.taskId === taskId)
    )
    console.log('加载的任务图片:', taskPhotos)
    return taskPhotos
  } catch (error) {
    console.error('加载任务图片失败:', error)
    return []
  }
}

// 删除任务相关图片
const deleteTaskPhoto = async (photoId: string) => {
  try {
    await photosStorage.deletePhoto(photoId)
    ElMessage.success($t('common.photoDeletedSuccess'))
  } catch (error) {
    console.error('删除图片失败:', error)
    ElMessage.error($t('common.photoDeleteError'))
  }
}

onMounted(() => {
  console.log('学习任务页面加载完成')
  // 加载任务相关图片
  loadTaskPhotos()
})
</script>

<style scoped>
.learning-tasks {
  padding: 24px;
  background: #f5f7fa;
  min-height: 100%;
}

/* 页面标题 */
.page-header {
  margin-bottom: 24px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

/* 状态标签栏 */
.status-tabs {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 16px 24px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.tabs-left {
  flex: 1;
}

.tabs-right {
  margin-left: 24px;
}
  border-radius: 1px;
}

/* 筛选功能栏 */
.filter-section {
  margin-bottom: 24px;
  padding: 20px 24px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 16px;
}

.search-form .el-form-item {
  margin-bottom: 0;
}
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  align-items: end;
}

:deep(.el-form-item) {
  margin-bottom: 0;
}

:deep(.el-form-item__label) {
  font-size: 14px;
  color: #606266;
}

/* 任务列表表格 */
.tasks-table-section {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.tasks-table {
  border-radius: 8px;
}

:deep(.el-table__header) {
  background: #f8f9fa;
}

:deep(.el-table th) {
  background: #f8f9fa;
  color: #606266;
  font-weight: 600;
  border-bottom: 1px solid #e4e7ed;
}

:deep(.el-table td) {
  border-bottom: 1px solid #f0f0f0;
}

/* 数据名称单元格 */
.task-name-cell {
  display: flex;
  align-items: center;
  gap: 12px;
}

.task-icon {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  background: #f0f9ff;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.task-icon img {
  width: 24px;
  height: 24px;
  object-fit: contain;
}

.task-info {
  flex: 1;
}

.task-title {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.task-description {
  font-size: 12px;
  color: #909399;
  line-height: 1.4;
}

/* 任务时间 */
.task-time {
  font-size: 14px;
  color: #606266;
}

/* 状态列 */
.task-status {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.status-item {
  display: flex;
  align-items: center;
  gap: 6px;
}

.status-icon {
  width: 16px;
  height: 16px;
  object-fit: contain;
}

.status-label {
  font-size: 12px;
  color: #606266;
}

.status-item.completed .status-label {
  color: #67c23a;
}

/* 操作列 */
.task-actions {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

:deep(.el-button--primary.is-link) {
  color: #409EFF;
  font-size: 14px;
  padding: 0;
  height: auto;
  border: none;
  background: none;
}

:deep(.el-button--primary.is-link:hover) {
  color: #66b1ff;
  text-decoration: underline;
}

/* 分页 */
.pagination-section {
  padding: 20px 24px;
  display: flex;
  justify-content: center;
  border-top: 1px solid #f0f0f0;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .category-section {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }

  .filter-form {
    flex-direction: column;
    align-items: stretch;
  }

  :deep(.el-form-item) {
    margin-right: 0;
  }
}

@media (max-width: 768px) {
  .learning-tasks {
    padding: 16px;
  }

  .category-tabs {
    flex-wrap: wrap;
  }

  .task-actions {
    flex-direction: column;
    align-items: flex-start;
  }

  :deep(.el-table .cell) {
    padding: 8px;
  }
}
</style>